package com.liang.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.liang.common.execption.NoStockException;
import com.liang.common.to.mq.OrderTo;
import com.liang.common.to.mq.StockDetailTo;
import com.liang.common.to.mq.StockLocked;
import com.liang.common.utils.R;
import com.liang.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.liang.gulimall.ware.entity.WareOrderTaskEntity;
import com.liang.gulimall.ware.feign.OrderFeignService;
import com.liang.gulimall.ware.feign.ProductFeignService;
import com.liang.gulimall.ware.service.WareOrderTaskDetailService;
import com.liang.gulimall.ware.service.WareOrderTaskService;
import com.liang.gulimall.ware.vo.OrderInfo;
import com.liang.gulimall.ware.vo.OrderItemVo;
import com.liang.gulimall.ware.vo.SkuHasStockVo;
import com.liang.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.common.utils.PageUtils;
import com.liang.common.utils.Query;

import com.liang.gulimall.ware.dao.WareSkuDao;
import com.liang.gulimall.ware.entity.WareSkuEntity;
import com.liang.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    WareOrderTaskService orderTaskService;
    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wareSkuEntityQueryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wareSkuEntityQueryWrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wareSkuEntityQueryWrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params), wareSkuEntityQueryWrapper);

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断如果还没有这个库存记录就新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities == null || entities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO 先远程查询sku name,如果失败不需要回滚
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));

                }
            } catch (Exception e) {
                System.out.println("远程调用先远程查询sku name失败");
            }
            wareSkuDao.insert(wareSkuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }


    private void unLockStock(Long skuId, Long wareId, Integer count, Long detailId) {
        WareSkuDao baseMapper = getBaseMapper();
        baseMapper.unLockStock(skuId, wareId, count);
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(detailId);
        wareOrderTaskDetailEntity.setLockStatus(2);//变为以解锁
        orderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }

    @Override
    public List<SkuHasStockVo> hasStock(List<Long> skuIds) {

        List<SkuHasStockVo> skuHasStockVoList = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count = baseMapper.getSkuStock(skuId);
            skuHasStockVo.setHasStock(count == null ? false : count > 0);
            skuHasStockVo.setSkuId(skuId);
            return skuHasStockVo;
        }).collect(Collectors.toList());

        return skuHasStockVoList;
    }

    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单
         */
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(wareOrderTaskEntity);

        //找到sku在那些仓库有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(orderItemVo -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(orderItemVo.getSkuId());
            //查仓库
            List<Long> wareIds = wareSkuDao.listWareIdWithHasStockBySkuId(orderItemVo.getSkuId());
            skuWareHasStock.setWareIds(wareIds);
            skuWareHasStock.setCount(orderItemVo.getCount());
            return skuWareHasStock;
        }).collect(Collectors.toList());

        //锁定库存
        for (SkuWareHasStock skuWareHasStock : collect) {
            boolean skuLock = false;
            Long skuId = skuWareHasStock.getSkuId();
            Integer count = skuWareHasStock.getCount();
            List<Long> wareIds = skuWareHasStock.getWareIds();
            if (wareIds == null || wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }
            //1、如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发给MQ
            //2、锁定失败。前面保存的工作单信息都回滚了。发送出去的消息，即使要解锁库存，由于在数据库查不到指定的id，所有就不用解锁
            for (Long wareId : wareIds) {
                Long col = wareSkuDao.lockSkuStock(skuId, wareId, count);
                if (col == 1) {
                    //锁成功
                    skuLock = true;
                    //TODO 发消息mq库存锁定成功
                    //保存库存工单
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
                    wareOrderTaskDetailEntity.setWareId(wareId);
                    wareOrderTaskDetailEntity.setTaskId(wareOrderTaskEntity.getId());
                    wareOrderTaskDetailEntity.setSkuId(skuId);
                    wareOrderTaskDetailEntity.setSkuNum(count);
                    wareOrderTaskDetailEntity.setLockStatus(1);
                    orderTaskDetailService.save(wareOrderTaskDetailEntity);
                    StockLocked stockLocked = new StockLocked();
                    stockLocked.setId(wareOrderTaskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    stockLocked.setStockDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLocked);
                    break;
                }
            }
            if (skuLock == false) {//某个没锁成功
                throw new NoStockException(skuId);
            }
        }


        return true;
    }

    /**
     * 库存自动解锁,补偿方案
     * /**
     * * 解锁
     * * 1、查询数据库关于这个订单锁定库存信息detailEntity
     * *   有：证明库存锁定成功了
     * *      解锁：订单状况
     * *          1、没有这个订单，必须解锁库存
     * *          2、有这个订单，不一定解锁库存
     * *              订单状态：已取消：解锁库存
     * *                      已支付：不能解锁库存
     */

    @Override
    public void unLock(StockLocked stockLocked) {
        StockDetailTo stockDetailTo = stockLocked.getStockDetailTo();
        Long detailId = stockDetailTo.getId();//detailId
        //查出最新的
        WareOrderTaskDetailEntity detailEntity = orderTaskDetailService.getById(detailId);
        if (detailEntity != null && detailEntity.getLockStatus() == 1) {
            //解锁
            Long id = stockLocked.getId();//工作单id
            WareOrderTaskEntity orderTaskEntity = orderTaskService.getById(id);
            String orderSn = orderTaskEntity.getOrderSn();
            //去订单系统查询这个订单号是否存在
            R r = orderFeignService.infoByOrderSn(orderSn);
            if (r.getCode() == 0) {
                OrderInfo orderInfo = r.getData("orderInfo", new TypeReference<OrderInfo>() {
                });
                if (orderInfo == null || orderInfo.getStatus() == 4) {//4:已取消
                    //解锁库存
                    unLockStock(stockDetailTo.getSkuId(), stockDetailTo.getWareId(),
                            stockDetailTo.getSkuNum(), stockDetailTo.getId());
                }
            } else {
                log.error("远程调用订单系统失败，请重试");
                //消息拒绝后重新放到队列里面
                throw new RuntimeException("远程调用订单系统失败");
            }

        } else {
            //无需解锁。库存锁定失败了。自己回滚了
        }
    }

    /**
     * 防止订单服务卡顿，库存解锁时状态改变不了，库存消息先到期
     *
     * @param order
     */
    @Transactional
    @Override
    public void unLock(OrderTo order) {
        WareOrderTaskEntity taskEntity = orderTaskService.getOne(
                new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", order.getOrderSn()));
        List<WareOrderTaskDetailEntity> detailEntities = orderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", taskEntity.getId()).eq("lock_status", 1));
        if (detailEntities != null && detailEntities.size() > 0) {
            for (WareOrderTaskDetailEntity detailEntity : detailEntities) {
                unLockStock(detailEntity.getSkuId(), detailEntity.getWareId(),
                        detailEntity.getSkuNum(), detailEntity.getId());
            }
        }

    }

    /**
     * 商品在那些创库有库存
     */
    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer count;
        private List<Long> wareIds;
    }

}